package com.ruoyi.kanaimqtt.common;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.ClientUtils;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class wxTokenUtil implements CommandLineRunner {
    @Autowired
    RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {
        upToken();
    }

    @Scheduled(cron = "0 0 0/2 * * ? ")
    public void updateToken(){
        upToken();
    }

    public  String getToken(){

        String accessToken = redisCache.getCacheObject("wx:");
        if (StringUtils.isEmpty(accessToken)) {
            String path = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+"wx362aecf1f5831614"+"&secret="+"a8e212ef04bffcbd3cfbd39d39fbd2e2";
            JSONObject jsonObject = null;
            try {
                jsonObject = ClientUtils.doGetMethod(path);
                accessToken = jsonObject.getString("access_token");
                log.info("获取token成功,accessToken:【{}】",accessToken);

                redisCache.setCacheObject("wx:",accessToken,3600, TimeUnit.SECONDS);
                return accessToken;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return accessToken;
    }

    public void  upToken(){

            String path = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+"wx362aecf1f5831614"+"&secret="+"a8e212ef04bffcbd3cfbd39d39fbd2e2";
            JSONObject jsonObject = null;
            try {
                jsonObject = ClientUtils.doGetMethod(path);
                String accessToken = jsonObject.getString("access_token");

                redisCache.setCacheObject("wx:",accessToken,3600, TimeUnit.SECONDS);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


}
